<%@ page contentType="text/html;charset=UTF-8" %>
<script>
var touchtime;
$(document).ready(function() {$('#purchaseOrderTable').bootstrapTable({

    //请求方法
    method: 'get',
    //类型json
    dataType: "json",
    //显示刷新按钮
    showRefresh: true,
    //显示切换手机试图按钮
    showToggle: true,
    //显示 内容列下拉框
    showColumns: true,
    //显示到处按钮
    showExport: true,
    //显示切换分页按钮
    showPaginationSwitch: true,
    //最低显示2行
    minimumCountColumns: 2,
    //是否显示行间隔色
    striped: true,
    //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
    cache: false,
    //是否显示分页（*）
    pagination: true,
    //排序方式
    sortOrder: "asc",
    //初始化加载第一页，默认第一页
    pageNumber: 1,
    //每页的记录行数（*）
    pageSize: 10,
    //可供选择的每页的行数（*）
    pageList: [10, 25, 50, 100],
    //这个接口需要处理bootstrap table传递的固定参数,并返回特定格式的json数据
    url: "${ctx}/purchase/purchaseOrder/data",
    //默认值为 'limit',传给服务端的参数为：limit, offset, search, sort, order Else
    //queryParamsType:'',
    ////查询参数,每次调用是会带上这个参数，可自定义
    queryParams: function(params) {
        var searchParam = $("#searchForm").serializeJSON();
        searchParam.pageNo = params.limit === undefined ? "1": params.offset / params.limit + 1;
        searchParam.pageSize = params.limit === undefined ? -1 : params.limit;
        searchParam.orderBy = params.sort === undefined ? "": params.sort + " " + params.order;
        return searchParam;
    },
    //分页方式：client客户端分页，server服务端分页（*）
    sidePagination: "server",
    //contextMenuTrigger: "right",
    //pc端 按右键弹出菜单
    //contextMenuTriggerMobile: "click",
    //手机端 弹出菜单，click：单击， press：长按。
    //contextMenu: '#context-menu',
    /*onContextMenuItem: function(row, $el) {
        if ($el.data("item") == "edit") {
            window.location = "${ctx}/purchase/purchaseOrder/form?id=" + row.id;
        } else if ($el.data("item") == "delete") {
            jp.confirm('确认要删除该供应链采购单记录吗？',
                function() {
                    jp.loading();
                    jp.get("${ctx}/purchase/purchaseOrder/delete?id=" + row.id,
                        function(data) {
                            if (data.success) {
                                $('#purchaseOrderTable').bootstrapTable('refresh');
                                jp.success(data.msg);
                            } else {
                                jp.error(data.msg);
                            }
                        })

                });

        }
    },*/

    /*onDblClickRow: function(row, $el, $event) {
    	console.log($el)
    	console.dir($el)
    	self.location.href="${ctx}/purchase/purchaseOrder/detail?id=" + row.id + ""
    },*/
    onClickRow:function(row, $el, $event) {
   
    	    if (touchtime == 0) {
    	        // set first click
    	        touchtime = new Date().getTime();
    	    } else {
    	        // compare first click to this click and see if they occurred within double click threshold
    	        if (((new Date().getTime()) - touchtime) < 800) {
    	            // double click occurred
    	            //alert("double clicked");
    	            touchtime = 0;
    	            self.location.href="${ctx}/purchase/purchaseOrder/detail?id=" + row.id + ""
    	        } else {
    	            // not a double click so set as a new first click
    	            touchtime = new Date().getTime();
    	        }
    	    }
    },
    columns: [{
        checkbox: true

    },
        {
            field: 'id',
            title: 'ID',
            sortable: true
        }
        ,{
            field: 'purchaseDate',
            title: '采购日期',
            sortable: true
        },{
            field: '操作',
            title: '操作',
            sortable: true,
            formatter: function(value, row, index) {
                if(row.state==0){

                }else{
                    return "双击查看";
                }
                return "<a onClick='edit("+row.id+",event)'>修改</a>"+"&nbsp;"+
                "<a onClick='finish("+row.id+",event)'>完成</a>";
            }

        }
        ,{
            field: 'state',
            title: '状态',
            sortable: true,
            formatter: function (value, row, index) {
                if(row.state==0){
                    return "<font color='red'>暂存</font>";
                }else{
                    return "<font color='green'>完成</font>";
                }
            }
        },
        {
            field: 'totalPlant',
            title: '数量',
            sortable: true

        },
        {
            field: 'totalPrice',
            title: '总价',
            sortable: true,
            formatter: function (value, row, index) {
                var price=parseFloat(value);
                return price.toFixed(2);
            }

        }
        ,{
            field: 'remarks',
            title: '备注',
            sortable: true

        }
        ,{
            field: 'supplierName',
            title: '供应商',
            sortable: true

        },
        {
            field: 'contractName',
            title: '合同名称',
            sortable: true

        },
        {
            field: 'contractNo',
            title: '合同编号',
            sortable: true

        }/*,
        {
            field: 'deliveryDate',
            title: '交货日期',
            sortable: true

        },
        {
            field: ' isTax',
            title: '是否含税',
            sortable: true

        },
        {
            field: 'tax',
            title: '税点',
            sortable: true

        },
        {
            field: 'invoiceType',
            title: '发票类型',
            sortable: true

        }*//*,{
            field: 'createBy.name',
            title: '创建人',
            sortable: true
        }*/
        /*,{
            field: 'createDate',
            title: '创建时间',
            sortable: true

        },{
            field: 'updateBy.name',
            title: '修改人',
            sortable: true
        }
        */
        ,{
            field: 'updateDate',
            title: '更新时间',
            sortable: true

        }
        ]

});


	  if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){//如果是移动端


		  $('#purchaseOrderTable').bootstrapTable("toggleView");
		}

	  $('#purchaseOrderTable').on('check.bs.table uncheck.bs.table load-success.bs.table ' +
                'check-all.bs.table uncheck-all.bs.table', function () {
            $('#remove').prop('disabled', ! $('#purchaseOrderTable').bootstrapTable('getSelections').length);
            $('#edit').prop('disabled', $('#purchaseOrderTable').bootstrapTable('getSelections').length!=1);
        });

		$("#btnImport").click(function(){
			jp.open({
			    type: 1,
			    area: [500, 300],
			    title:"导入数据",
			    content:$("#importBox").html() ,
			    btn: ['下载模板','确定', '关闭'],
				    btn1: function(index, layero){
					  window.location='${ctx}/purchase/purchaseOrder/import/template';
				  },
			    btn2: function(index, layero){
				        var inputForm =top.$("#importForm");
				        var top_iframe = top.getActiveTab().attr("name");//获取当前active的tab的iframe
				        inputForm.attr("target",top_iframe);//表单提交成功后，从服务器返回的url在当前tab中展示
				        inputForm.onsubmit = function(){
				        	jp.loading('  正在导入，请稍等...');
				        }
				        inputForm.submit();
					    jp.close(index);
				  },

				  btn3: function(index){
					  jp.close(index);
	    	       }
			});
		});

	  $("#search").click("click", function() {// 绑定查询按扭
		  $('#purchaseOrderTable').bootstrapTable('refresh');
		});

	 $("#reset").click("click", function() {// 绑定查询按扭
		  $("#searchForm  input").val("");
		  $("#searchForm  select").val("");
		  $("#searchForm  .select-item").html("");
		  $('#purchaseOrderTable').bootstrapTable('refresh');
		});

		$('#createDate').datetimepicker({
			 format: "YYYY-MM-DD HH:mm:ss"
		});
		$('#updateDate').datetimepicker({
			 format: "YYYY-MM-DD HH:mm:ss"
		});

	});

  function getIdSelections() {
        return $.map($("#purchaseOrderTable").bootstrapTable('getSelections'), function (row) {
            return row.id
        });
    }

  function deleteAll(){

		jp.confirm('确认删除该供应链采购单记录吗？', function(){
			jp.loading();
			jp.get("${ctx}/purchase/purchaseOrder/deleteAll?ids=" + getIdSelections(), function(data){
         	  		if(data.success){
         	  			$('#purchaseOrderTable').bootstrapTable('refresh');
         	  			jp.success(data.msg);
         	  		}else{
         	  			jp.error(data.msg);
         	  		}
         	  	})

		})
  }
  function edit(id,e){
	  e. stopPropagation();
	  //修改时打开的界面改成非弹出层
	  window.location = "${ctx}/purchase/purchaseOrder/updatePurchaseOrder?id=" + id;
  }
  
  function finish(id,e){
	  e. stopPropagation();
	  jp.confirm('确认完成采购并生成入库单吗？', function(){
		  jp.loading();  
		  //提交数据
	      $.ajax({
	          url:"${ctx}/purchase/purchaseOrder/finishPurchaseOrderAndCreateWarehouseReceipt?purchaseOrderId="+id,
	          type:"post",
	          
	          success:function(data){
	              if(data.message=="1"){
	            	  $('#purchaseOrderTable').bootstrapTable('refresh');
	            	  jp.success("操作成功");
	              }
	          },
	          error:function(e){
	        	  jp.error("操作失败");
	
	          }
	      });
	  })
  }

</script>